<template>
	<div class="incoming-inspection-list">
		<div class="page-header"><h2>到货检验管理</h2></div>
		<div class="action-bar">
			<div class="left-actions">
				<el-button type="primary" @click="handleAdd" icon="Plus">新增</el-button>
				<el-button type="success" @click="handleExport" icon="Download">导出</el-button>
				<el-button v-if="selectedRows.length > 0" type="info" @click="handleExportSelected" icon="Download">导出选中({{ selectedRows.length }})</el-button>
			</div>
			<div class="right-actions">
				<el-input v-model="searchText" placeholder="请搜索" class="search-input" clearable @keyup.enter="handleSearch">
					<template #append>
						<el-button @click="handleSearch" icon="Search" />
					</template>
				</el-input>
				<el-button @click="handleRefresh" icon="Refresh" />
			</div>
		</div>
		<el-table :data="rows" v-loading="loading" stripe border style="width: 100%" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column type="index" label="序号" width="60" />
			<el-table-column prop="inspectionOrderNumber" label="检验单号" width="180" />
			<el-table-column prop="inspectionSubject" label="检验单主题" width="150" />
			<el-table-column label="检验日期" width="130">
				<template #default="scope">{{ formatDate(scope.row.inspectionDate) }}</template>
			</el-table-column>
			<el-table-column label="物品概要" width="200">
				<template #default="scope">
					<div class="item-summary" @click="showItemSummary(scope.row)">
						<span>{{ getItemSummaryText(scope.row) }}</span>
						<el-icon class="summary-arrow"><ArrowDown /></el-icon>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="检验人" width="120">
				<template #default="scope">{{ scope.row.inspectorName || '-' }}</template>
			</el-table-column>
			<el-table-column label="所在部门" width="120">
				<template #default="scope">{{ scope.row.departmentName || '质检部' }}</template>
			</el-table-column>
			<el-table-column label="采购单号" width="150">
				<template #default="scope">{{ scope.row.purchaseOrderNumber || '-' }}</template>
			</el-table-column>
			<el-table-column label="备注" width="120">
				<template #default="scope">{{ scope.row.remarks || '-' }}</template>
			</el-table-column>
			<el-table-column label="操作" width="120" fixed="right">
				<template #default="scope">
					<el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container">
			<div class="pagination-info">共 {{ totalCount }} 项数据</div>
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5,10,20,50]" :total="totalCount" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>
		<IncomingInspectionForm v-model:visible="formVisible" @success="handleFormSuccess" />
		
		<!-- 物品概要弹出框 -->
		<el-dialog v-model="itemSummaryVisible" title="物品概要" width="500px" :close-on-click-modal="false">
			<div class="item-summary-dialog">
				<div v-for="item in currentItemSummary" :key="item.id" class="item-row">
					<span class="item-name">{{ item.name }}</span>
					<span class="item-quantity">: {{ item.quantity }}</span>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { incomingInspectionApi, type GoodsArrivalInspectionDto, type GetGoodsArrivalInspectionListQuery } from '@/api/incomingInspectionApi'
import IncomingInspectionForm from './IncomingInspectionForm.vue'
import { ArrowDown, Download } from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(false)
const rows = ref<GoodsArrivalInspectionDto[]>([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')
const formVisible = ref(false)
const selectedRows = ref<GoodsArrivalInspectionDto[]>([])
const itemSummaryVisible = ref(false)
const currentItemSummary = ref<any[]>([])

const queryParams = reactive<GetGoodsArrivalInspectionListQuery>({
	pageIndex: 1,
	pageSize: 10,
	inspectionSubject: '',
	inspectionOrderNumber: ''
})

onMounted(() => load())

const load = async () => {
	try {
		loading.value = true
		queryParams.pageIndex = currentPage.value
		queryParams.pageSize = pageSize.value
		queryParams.inspectionSubject = searchText.value
		const res = await incomingInspectionApi.getList(queryParams)
		if (res.code === 200) {
			rows.value = res.data.pageData || []
			totalCount.value = res.data.totalCount || 0
		} else {
			ElMessage.error(res.message || '获取列表失败')
		}
	} catch (e:any) {
		ElMessage.error(e.message || '获取列表失败')
	} finally {
		loading.value = false
	}
}

const handleSearch = () => { currentPage.value = 1; load() }
const handleRefresh = () => load()
const handleSizeChange = (s:number) => { pageSize.value = s; currentPage.value = 1; load() }
const handleCurrentChange = (p:number) => { currentPage.value = p; load() }
const handleAdd = () => { formVisible.value = true }
const handleFormSuccess = () => { formVisible.value = false; load(); ElMessage.success('新增成功') }
const handleView = (row: GoodsArrivalInspectionDto) => { router.push(`/IncomingInspectionDetail/${row.id}`) }

// 处理选择变化
const handleSelectionChange = (selection: GoodsArrivalInspectionDto[]) => {
	selectedRows.value = selection
}

// 显示物品概要
const showItemSummary = (row: GoodsArrivalInspectionDto) => {
	// 模拟物品概要数据，实际应该从API获取
	currentItemSummary.value = [
		{ id: 1, name: '产品0215', quantity: 3 },
		{ id: 2, name: '产品032', quantity: 1 },
		{ id: 3, name: '产品', quantity: 2 },
		{ id: 4, name: '产品三一', quantity: 2 },
		{ id: 5, name: '新产品', quantity: 2 }
	]
	itemSummaryVisible.value = true
}

// 获取物品概要显示文本
const getItemSummaryText = (row: GoodsArrivalInspectionDto) => {
	return '新产品等10项'
}

// 导出功能
const handleExport = async () => {
	try {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请先选择要导出的数据')
			return
		}
		
		await exportToExcel(selectedRows.value, '到货检验数据')
		
	} catch (error) {
		ElMessage.error('导出失败')
		console.error('导出错误:', error)
	}
}

// 导出选中项
const handleExportSelected = async () => {
	try {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请先选择要导出的数据')
			return
		}
		
		await exportToExcel(selectedRows.value, '到货检验数据_选中项')
		
	} catch (error) {
		ElMessage.error('导出失败')
		console.error('导出错误:', error)
	}
}

// 通用导出Excel函数
const exportToExcel = async (data: GoodsArrivalInspectionDto[], sheetName: string) => {
	// 准备导出数据
	const exportData = data.map(row => ({
		'检验单号': row.inspectionOrderNumber || '-',
		'检验单主题': row.inspectionSubject || '-',
		'检验日期': formatDate(row.inspectionDate) || '-',
		'物品概要': getItemSummaryText(row),
		'检验人': row.inspectorName || '-',
		'所在部门': row.departmentName || '质检部',
		'采购单号': row.purchaseOrderNumber,
		'备注': row.remarks || '-'
	}))
	
	// 使用xlsx库导出Excel
	const XLSX = await import('xlsx')
	const ws = XLSX.utils.json_to_sheet(exportData)
	const wb = XLSX.utils.book_new()
	XLSX.utils.book_append_sheet(wb, ws, sheetName)
	
	// 生成文件名
	const fileName = `${sheetName}_${new Date().toISOString().split('T')[0]}.xlsx`
	XLSX.writeFile(wb, fileName)
	
	ElMessage.success(`成功导出 ${data.length} 条数据到 ${fileName}`)
}

const formatDate = (d?: string) => d ? new Date(d).toLocaleDateString('zh-CN') : '-'
const statusType = (s?: string) => s === '已完成' ? 'success' : s === '检验中' ? 'warning' : s === '已驳回' ? 'danger' : 'info'
</script>

<style scoped>
.incoming-inspection-list { padding: 20px; }
.page-header { margin-bottom: 20px; }
.page-header h2 { margin: 0; color: #303133; }
.action-bar { display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; padding:16px; background:#f5f7fa; border-radius:4px; }
.left-actions { display:flex; gap:10px; }
.right-actions { display:flex; align-items:center; gap:10px; }
.search-input { width:300px; }
.pagination-container { display:flex; justify-content:space-between; align-items:center; margin-top:20px; padding:16px; background:#f5f7fa; border-radius:4px; }
.pagination-info { color:#606266; font-size:14px; }

/* 物品概要样式 */
.item-summary {
	display: flex;
	align-items: center;
	justify-content: space-between;
	cursor: pointer;
	padding: 4px 8px;
	border-radius: 4px;
	transition: background-color 0.2s;
}

.item-summary:hover {
	background-color: #f0f9ff;
}

.summary-arrow {
	font-size: 12px;
	color: #909399;
	transition: transform 0.2s;
}

.item-summary:hover .summary-arrow {
	transform: rotate(180deg);
}

/* 物品概要弹出框样式 */
.item-summary-dialog {
	max-height: 300px;
	overflow-y: auto;
}

.item-row {
	display: flex;
	justify-content: space-between;
	padding: 8px 0;
	border-bottom: 1px solid #f0f0f0;
}

.item-row:last-child {
	border-bottom: none;
}

.item-name {
	font-weight: 500;
	color: #303133;
}

.item-quantity {
	color: #606266;
}

/* 表格选择列样式 */
:deep(.el-table__selection) {
	text-align: center;
}
</style> 